import LoginApi from '@/apis/login';
import { userStore, pinia } from '@/stores'
import CommonApi from '../apis/common';
const store = userStore(pinia);

/**
 * @description 获取当前账号归属医院列表
 */
function $getFactoryList() {
	return LoginApi.getAffiliatedOrgs({
		origin: 'miniProgram'
	}).then((res) => {
		if(res.status === 'success' && Array.isArray(res.result)) {
			const hospitalList = res.result.filter(val => val?.factoryType === 'hospital' && val?.memberStatus === 'active' && val?.status === 'enable')
			store.setHospitalList(hospitalList);
		} else {
			store.setInitHospital()
		}
	}).catch((err) => {
		store.setInitHospital()
	});
}

function $changeHospital(info) {
	return new Promise((resolve, reject) => {
		CommonApi.changeHospital({orgID: info.id, origin: 'miniProgram'}).then((res) => {
			if ( res.status === 'success' ) {
				const hospitalList = store.hospitalList;
				hospitalList.forEach(v => {
					if (v.id !== info.id) {
						v.lastState = 'n'
					} else {
						v.lastState = 'y'
					}
				})
				store.setHospitalList(hospitalList);
				resolve(res)
			} else {
				reject(res)
			}
		}).catch(() => reject(res))
	})
}

export {
	$getFactoryList,
	$changeHospital
}
